package com.vip.jwt.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    /**
     * 签名密钥
     */
    public static final String SECRET = "token!Q@W3e4r";

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 过期时间1天
     */
    private static final int EXPIRE_DAY = 1;

    /**
     * 生成token
     * @param username 用户名
     * @return
     */
    public static String createToken(String username) {
        Date currentDate = DateUtil.date();
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        return JWT.create()
                .withHeader(map)
                //发布时间
                .withIssuedAt(currentDate)
                .withClaim("username",username)
                //过期时间
                .withExpiresAt(DateUtil.offsetDay(currentDate,EXPIRE_DAY))
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 校验token
     */
    public static void verifyToken(String token){
        JWT.require(Algorithm.HMAC256(SECRET))
                .build()
                .verify(token);
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(reduceToken(token));
            return jwt.getClaim(SECRET).asString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 加头
     *
     * @param token
     * @return
     */
    private static String addToken(String token) {
        token = token.replaceAll("Bearer ","");
        token = "Bearer "+token;
        return token;
    }

    /**
     * 去头
     *
     * @param token
     * @return
     */
    private static String reduceToken(String token) {
        return token.replaceAll("Bearer ","");
    }

}
